const express = require('express')
require('dotenv').config()
const process = require('node:process')
const mongoose = require('mongoose')
// const session = require('express-session')
const cors = require('cors')
const passport = require('./middlewares/jwtAuthStrategy')

const logger = require('./middlewares/logger')
const indexRouter = require('./routes/index')
const tasksRouter = require('./routes/tasks/index')
const tagsRouter = require('./routes/tags/index')
const userRouter = require('./routes/users/index')
const projectsRouter = require('./routes/projects/index')
const notesRouter = require('./routes/notes/index')
const notificationRouter = require('./routes/notifications/index')
const messageRouter = require('./routes/messages/index')
const {app, server} = require('./socket/socket')

app.use(
  cors({
    origin: process.env.URL_FRONT,
    credentials: true,
    allowedHeaders: 'Origin, Content-Type, Accept, Authorization',
  }),
)

app.use(express.json())
app.use(passport.initialize())

app.use('/', indexRouter)
app.use('/tasks', tasksRouter)
app.use('/users', userRouter)
app.use('/projects', projectsRouter)
app.use('/notes', notesRouter)
app.use('/tags', tagsRouter)
app.use('/notifications', notificationRouter)
app.use('/messages', messageRouter)

mongoose.set('strictQuery', false)
app.use(logger)

const UrlBD = process.env.UrlBD || 'mongodb://127.0.0.1:27017/chill-base'
const PORT = process.env.PORT || 3000

async function start(PORT, UrlBD) {
  try {
    await mongoose.connect(UrlBD)
    server.listen(PORT, () => {
      console.log(`Сервер запущен на порту ${PORT}, подключен к БД через ${UrlBD}`)
    })
  } catch (e) {
    console.error('Ошибка подключения к БД:', e)
    process.exit(1) // Корректное завершение процесса при ошибке
  }
}

start(PORT, UrlBD)

process.on('uncaughtException', (err) => {
  console.error('Необработанное исключение:', err)
  process.exit(1)
})

process.on('unhandledRejection', (reason, promise) => {
  console.error('Необработанное отклонение промиса:', promise, 'Причина:', reason)
  process.exit(1)
})
